async function load(){
  const data = await apiGet('/api/list');
  const tbody = document.querySelector('#list tbody');
  tbody.innerHTML = '';
  data.forEach(r=>{
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td>${r.customer}</td>
      <td>${r.mac}</td>
      <td><input class="edit-date" type="date" value="${r.expiry}"
               onchange="updateExpiry(${r.id},this.value)"></td>
      <td>${r.status}</td>
      <td><button onclick="delRow(${r.id})">删除</button></td>`;
    if (r.status.includes('已过期')) tr.style.color = '#e74c3c';
    if (r.status.includes('即将过期')) tr.style.color = '#f39c11';
    tbody.appendChild(tr);
  });
}

document.getElementById('addForm').onsubmit = async (e)=>{
  e.preventDefault();
  const fd = new FormData(e.target);
  const js = await apiPostForm('/api/add', fd);
  showAlert(js.alert);
  e.target.reset();
  load();
};

async function updateExpiry(id,newDate){
  const js = await apiPost('/api/update', {idx:id, expiry:newDate});
  showAlert(js.alert);
  load();
}

async function delRow(id){
  if(!confirm('确定删除？')) return;
  await apiPost('/api/delete', {idx:id});
  load();
}

function showAlert(msg){
  const box = document.getElementById('alertBox');
  if(msg){
    box.textContent = msg;
    box.className = msg.includes('已过期')?'alert-bar alert-red':'alert-bar alert-orange';
    box.style.display = 'block';
  } else box.style.display = 'none';
}

load();
